package com.monitoring.domain.service;

import com.monitoring.domain.entity.Device;
import com.monitoring.domain.entity.AirConditioner;
import com.monitoring.domain.entity.ElectricMeter;
import com.monitoring.domain.repository.DeviceRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class DeviceManagementService {
    private final DeviceRepository deviceRepository;
    
    public DeviceManagementService(DeviceRepository deviceRepository) {
        this.deviceRepository = deviceRepository;
    }
    
    // 添加设备（适配测试中的方法名）
    public <T extends Device> T addDevice(T device) {
        return deviceRepository.save(device);
    }
    
    // 获取设备（适配测试中的方法名）
    public Optional<Device> getDevice(Long id) {
        return deviceRepository.findById(id);
    }
    
    // 获取所有设备
    public List<Device> getAllDevices() {
        return deviceRepository.findAll();
    }
    
    // 根据类型获取设备
    public List<Device> getDevicesByType(String type) {
        return deviceRepository.findByType(type);
    }
    
    // 根据位置获取设备
    public List<Device> getDevicesByLocation(String location) {
        return deviceRepository.findByLocation(location);
    }
    
    // 获取活跃设备
    public List<Device> getActiveDevices() {
        return deviceRepository.findActiveDevices();
    }
    
    // 删除设备
    public void deleteDevice(Long id) {
        deviceRepository.deleteById(id);
    }
    
    // 设备是否存在
    public boolean deviceExists(Long id) {
        return deviceRepository.existsById(id);
    }
    
    // 记录电表读数
    public ElectricMeter recordElectricMeterReading(long meterId, double reading) {
        Optional<Device> optionalDevice = deviceRepository.findById(meterId);
        if (optionalDevice.isPresent() && optionalDevice.get() instanceof ElectricMeter) {
            ElectricMeter meter = (ElectricMeter) optionalDevice.get();
            meter.updateReading(reading);
            return deviceRepository.save(meter);
        }
        throw new IllegalArgumentException("电表不存在或类型错误");
    }
}